﻿using System;
using System.Collections.Generic;
using System.Text;

namespace System.Data.SugarClient
{

	internal class SugarVarDef
	{
		#region Fields

		string _defaultValue;
		string _label;
		string _name;
		IDictionary<string, string> _options;
		bool _required;
		string _type;

		#endregion

		#region Propreties

		public string DefaultValue
		{
			get { return _defaultValue; }
		}

		public string Label
		{
			get { return _label; }
		}

		public string Name
		{
			get { return _name; }
		}

		public IDictionary<string, string> Options
		{
			get { return _options; }
		}

		public bool Required
		{
			get { return _required; }
		}

		public string Type
		{
			get { return _type; }
		}

		public Type DataType
		{
			get
			{
				switch (this.Type.ToLower())
				{
					case "assigned_user_name": return typeof(string);
					case "bool": return typeof(bool);
					case "date": return typeof(DateTime);
					case "datetime": return typeof(DateTime);
					case "enum": return typeof(int);
					case "id": return typeof(Guid);
					case "int": return typeof(int);
					case "name": return typeof(string);
					case "parent_type": return typeof(string);
					case "phone": return typeof(string);
					case "relate": return typeof(string);
					case "string": return typeof(string);
					case "text": return typeof(string);
					case "varchar": return typeof(string);
					// default: return typeof(string);
				}
				throw new SugarException(string.Format("Unknown Type {0}.", this.Type));
			}
		}

		#endregion

		internal static SugarVarDef Create(SugarSoapV1.field source)
		{
			SugarVarDef value = new SugarVarDef();
			value._defaultValue = source.default_value;
			value._label = source.label;
			value._name = source.name;
			value._options = ToDictionary(source.options);
			value._required = (source.required !=0 );
			value._type = source.type;
			return value;
		}

		internal static IDictionary<string, string> ToDictionary(
			SugarSoapV1.name_value[] namevalues)
		{
			Dictionary<string, string> values = new Dictionary<string, string>();
			foreach (SugarSoapV1.name_value namevalue in namevalues)
			{
				values[namevalue.name] = namevalue.value;
			}
			return values;
		}
	}
}
